package com.tanhua.app.controllerservice;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.api.db.UserApi;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.FriendsApi;
import com.tanhua.api.mongo.RecommendUserApi;
import com.tanhua.api.mongo.UserLikeApi;
import com.tanhua.api.mongo.VisitorsApi;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.mongo.Visitors;
import com.tanhua.domain.vo.*;
import com.tanhua.template.AipFaceTemplate;
import com.tanhua.template.HuanXinTemplate;
import com.tanhua.template.OssTemplate;
import com.tanhua.template.SmsTemplate;
import com.tanhua.utils.JwtUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Reference
    private UserApi userApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Reference
    private FriendsApi friendsApi;
    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private VisitorsApi visitorsApi;
    @Reference
    private RecommendUserApi recommendUserApi;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;




    public ResponseEntity findByPhone(String phone){
        User user = userApi.findPhone(phone);
        return ResponseEntity.ok(user);
    }


    public ResponseEntity saveUser(User user){
        Long id = userApi.save(user);
        return ResponseEntity.ok(id);
    }


    @PostMapping(name = "手机号发短信",value = "/login")
    public ResponseEntity login(String phone){
        //发短信
        //String code = RandomUtil.randomNumbers(6);
        //smsTemplate.sendSms(phone,code);
        //验证码放入redis中
        String code="123456";
        stringRedisTemplate.opsForValue().set("SMS_CODE_"+phone,code, Duration.ofMinutes(5));

        return ResponseEntity.ok(null);
    }




    //登录注册
    public ResponseEntity loginVerification(String phone,String verificationCode){

        //2 就页面用户填写的验证码和redis的验证码对比
        String code = stringRedisTemplate.opsForValue().get("SMS_CODE_" + phone);
        if(!StrUtil.equals(verificationCode,code)){
            //不一致
            return ResponseEntity.status(500).body("验证码错误");
        }


        //3 正确(带着手机号去数据库查询是否有该用户)
        User loginUser = userApi.findPhone(phone);

        //初始值（老用户）
        Boolean isNew=false;

        if(loginUser==null){
            //新用户(注册)
            loginUser = new User();
            loginUser.setPhone(phone);
            Long id = userApi.save(loginUser);
            loginUser.setId(id);
            isNew=true;

            //新用户还有保存成环信用户
            huanXinTemplate.register(id);
        }




        //优化1：只要匹配成功 redis中的验证码要删除
        stringRedisTemplate.delete("SMS_CODE_" + phone);

        //优化2：将登录用户加密成token 放入redis中 且返回给浏览器
        String token = JwtUtil.createToken(loginUser, "tanhua");
        //loginUser--字符串json
        String json_user = JSON.toJSONString(loginUser);
        stringRedisTemplate.opsForValue().set("TOKEN_"+token,json_user,1, TimeUnit.DAYS);

        // 设定返回值
        Map returnMap=new HashMap();
        returnMap.put("token",token);
        returnMap.put("isNew",isNew);


        //实现功能
        //将任务交给中间件  type=0101
            //编写代码创建一个生产者往指定的中间件中发送生产任务的数据
        Map<String,String> map=new HashMap<String,String>();
        map.put("userId",loginUser.getId().toString());
        map.put("type",isNew?"0102":"0101");
        String date = DateUtil.format(new Date(),"yyyy-MM-dd");
        map.put("logTime", date);
        rocketMQTemplate.convertAndSend("tanhua-log",map);


        return ResponseEntity.ok(returnMap);
    }

    public ResponseEntity loginReginfo(String token, UserInfo userInfo) {
        //1 根据token从redis中获取注册用户（抽取）
        User user=fromRedisUser(token);
        //2 将注册中户的id赋值给userInfo的id
        userInfo.setId(user.getId());
        //3 调用服务提供者的方法进行保存
        userInfoApi.saveUserInfo(userInfo);
        return ResponseEntity.ok(null);


    }


    //根据token从redis中获取注册用户（抽取工具）
    public User fromRedisUser(String token) {

        String json_user = stringRedisTemplate.opsForValue().get("TOKEN_" + token);
        //json--java对象
        User user = JSON.parseObject(json_user, User.class);



        return user;

    }

    public ResponseEntity head(String token, MultipartFile headPhoto) throws IOException {

        // 人脸识别
        boolean flg = aipFaceTemplate.detect(headPhoto.getBytes());

        if(!flg){
            // 失败--给app提示
            return ResponseEntity.status(500).body("不是人脸");
        }
        // 成功--上传到oss中
        String path = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        System.out.println(path);
        // 记录地址 记录当前注册用户的id(redis获取)
        UserInfo userInfo = new UserInfo();
        userInfo.setAvatar(path);
        userInfo.setCoverPic(path);
        User user = fromRedisUser(token);
        userInfo.setId(user.getId());


        // 调用服务的修改方法
        userInfoApi.update(userInfo);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity findUserInfo(Long id) {
        UserInfo userInfo=userInfoApi.findUserInfo(id);
        //userInfo-UserInfoVo
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo,userInfoVo);
        userInfoVo.setAge(userInfo.getAge().toString());
        return ResponseEntity.ok(userInfoVo);
    }

    public ResponseEntity updateInfo(String token, UserInfo userInfo) {
        User user = fromRedisUser(token);
        userInfo.setId(user.getId());
        userInfoApi.update(userInfo);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity counts() {

        // 1 查询互相喜欢的count
        long eachLoveCount=friendsApi.findeachLoveCount(UserHolder.getUser().getId());

        //2 查询喜欢的count
        long loveCount=userLikeApi.findloveCount(UserHolder.getUser().getId());

        //3 查询粉丝的count
        long fanCount=userLikeApi.findfanCount(UserHolder.getUser().getId());


        //4 封装vo返回
        CountsVo vo = new CountsVo(eachLoveCount, loveCount, fanCount);

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findBytype(String type, Integer page, Integer pagesize) {

        PageBeanVo pageBeanVo=null;

        List<UserLikeListVo> voList=new ArrayList();
        //1 根据type做switch判断
        switch (type){
            case "1":{
                //2 如果type=1 查询好友数据tanhua_friends
                pageBeanVo=friendsApi.findFriendsList(page,pagesize,UserHolder.getUser().getId());
                List<Friend> items = (List<Friend>) pageBeanVo.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (Friend friend : items) {
                        UserInfo userInfo = userInfoApi.findUserInfo(friend.getFriendId());
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtil.copyProperties(userInfo,vo);
                        voList.add(vo);
                    }
                }
                break;
            }
            case "2":{
                //3 如果type=2 查询我喜欢的用户数据user_like
                pageBeanVo=userLikeApi.findUserListList(page,pagesize,UserHolder.getUser().getId());
                List<UserLike> items = (List<UserLike>) pageBeanVo.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (UserLike userLike : items) {
                        UserInfo userInfo = userInfoApi.findUserInfo(userLike.getLikeUserId());
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtil.copyProperties(userInfo,vo);
                        voList.add(vo);
                    }
                }
                break;
            }
            case "3":{
                //4 如果type=3 查询喜欢我的用户数据user_like
                pageBeanVo=userLikeApi.findUserList(page,pagesize,UserHolder.getUser().getId());
                List<UserLike> items = (List<UserLike>) pageBeanVo.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (UserLike userLike : items) {
                        UserInfo userInfo = userInfoApi.findUserInfo(userLike.getUserId());
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtil.copyProperties(userInfo,vo);
                        voList.add(vo);
                    }
                }
                break;
            }
            case "4":{
                //5 如果type=4 查询访客数据 visitors
                pageBeanVo= visitorsApi.findVisitorsList(page,pagesize,UserHolder.getUser().getId());
                List<Visitors> items = (List<Visitors>) pageBeanVo.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (Visitors visitors : items) {
                        UserInfo userInfo = userInfoApi.findUserInfo(visitors.getVisitorUserId());
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtil.copyProperties(userInfo,vo);
                        //猿粪值
                        RecommendUser recommendUser = recommendUserApi.findScore(visitors.getVisitorUserId().intValue(), UserHolder.getUser().getId());
                        if(recommendUser==null){
                            recommendUser=new RecommendUser();
                            recommendUser.setScore(99.99);
                        }
                        vo.setMatchRate(recommendUser.getScore().intValue());
                        voList.add(vo);
                    }
                }
                break;
            }

        }

        //6 封装vo数据返回  UserLikeListVo
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }


    //既要完成互相喜欢的取消喜欢 也要完成喜欢的取消喜欢
    public ResponseEntity unlike(Integer uid) {

        // 判断是否为好友
        Boolean flg=friendsApi.isFriends(uid,UserHolder.getUser().getId());
        if(flg==true){
            //是---（完成互相喜欢的取消喜欢）
            //1 解除好友关系
            friendsApi.deleteFriends(UserHolder.getUser().getId(),uid);
            //2 新增一条粉丝数据
            UserLike userLike = new UserLike();
            userLike.setCreated(System.currentTimeMillis());
            userLike.setUserId(uid.longValue());
            userLike.setLikeUserId(UserHolder.getUser().getId());
            userLikeApi.saveFans(userLike);
        }else{
            //不是---(完成喜欢的取消喜欢)
            //1 删除一条喜欢的数据
            userLikeApi.deleteUserLike(UserHolder.getUser().getId(),uid);
        }

        return ResponseEntity.ok(null);
    }

    public ResponseEntity unfans(Integer uid) {

        //绑定好友关系（2条数据）
        friendsApi.contacts(uid,UserHolder.getUser().getId());
        //删除一条粉丝数据
        userLikeApi.deleteUserLike(uid.longValue(),UserHolder.getUser().getId().intValue());

        return ResponseEntity.ok(null);
    }
}
